const MoviesModel = require('../models/movies')
const express = require('express')
const fs = require('fs')
const async = require('async')
const router = express.Router()
const cheerio = require('cheerio')
router.get('/movies', function(req, res, next) {
  let page = req.query.p || 1;
  page = page * 1;
  let size = req.query.size || 10;
  size = size * 1;
  let block = req.query.block;
  let pCount = MoviesModel.getCount()
  let pMovies = MoviesModel.getMovies(page, size, block)
  Promise.all([pCount, pMovies]).then(result => {
    let movies = result[1].map(movie => {
      return movie
    })
    res.send({
      result: movies
    })
  }).catch(next)
})
router.get('/rank/movies', function(req, res, next) {
  let page = req.query.p || 1;
  page = page * 1;
  let size = req.query.size || 10;
  size = size * 1;
  let block = req.query.block;
  let pCount = MoviesModel.getCount()
  let pMovies = MoviesModel.getRankMovies(page, size, block)
  Promise.all([pCount, pMovies]).then(result => {
    let movies = result[1].map(movie => {
      return movie
    })
    res.send({
      result: movies
    })
  }).catch(next)
})
router.get('/tag/movies', function(req, res, next) {
  let page = req.query.p || 1;
  page = page * 1;
  let size = req.query.size || 10;
  size = size * 1;
  let tag = req.query.tag;
  console.log(page, size, tag);
  let pCount = MoviesModel.getCount()
  let pMovies = MoviesModel.getMoviesbyTag(page, size, tag)
  Promise.all([pCount, pMovies]).then(result => {
    let movies = result[1].map(movie => {
      return movie
    })
    res.send({
      result: movies
    })
  }).catch(next)
})

router.get('/search/movies', function(req, res, next) {
  let page = req.query.p || 1;
  page = page * 1;
  let size = req.query.size || 10;
  size = size * 1;
  let keyword = req.query.keyword;
  let pCount = MoviesModel.getCount()
  let pMovies = MoviesModel.getMoviesbyKeyword(page, size, keyword)
  Promise.all([pCount, pMovies]).then(result => {
    let movies = result[1].map(movie => {
      return movie
    })
    res.send({
      result: movies
    })
  }).catch(next)
})
router.get('/movies/:movieId', function(req, res, next) {
  const movieId = req.params.movieId
  Promise.all([
    MoviesModel.getOne(movieId),
    MoviesModel.incPv(movieId)
  ])
  .then(result => {
    res.send({
      result: result[0],
      pv: result[1]
    })
  })
  .catch(next)
})

module.exports = router
